package cn.edu.usst.cs.goldfish.booking.meetingroom.util;

import cn.edu.usst.cs.goldfish.booking.meetingroom.handler.GoldfishBookingException;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.Builder;
import lombok.Data;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Random;

/**
 * 邮件发送工具类
 */
@Component
public class EmailUtil {

    private final JavaMailSenderImpl mailSender;


    // 修改构造函数参数类型为接口类型JavaMailSender
    public EmailUtil(
            JavaMailSender mailSender
    ) {
        this.mailSender = (JavaMailSenderImpl) mailSender;
    }

    public void sendEmail(EmailInfo emailInfo) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(Objects.requireNonNull(mailSender.getUsername()));
            helper.setTo(emailInfo.getEmail());
            helper.setSubject("注册验证码");
            helper.setText(emailInfo.content, true);
            mailSender.send(message);
        } catch (MessagingException e) {
            throw new GoldfishBookingException("邮件发送失败：" + e.getMessage(), e);
        }
    }

    @Data
    @Builder
    public static class EmailInfo {
        String content;
        String email;
    }

}
